package cn.schoolwow.quickdao.module.initial.flow.database;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;

public class ExecuteCreateDatabaseFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        String driverClassName = flowContext.checkData("driverClassName", String.class);
        String jdbcUrl = flowContext.checkData("jdbcUrl", String.class);
        String username = flowContext.getData("username", String.class);
        String password = flowContext.getData("password", String.class);
        String queryDatabaseSQL = flowContext.checkData("queryDatabaseSQL", String.class);
        String createDatabaseSQL = flowContext.checkData("createDatabaseSQL", String.class);

        String rawJdbcUrl = jdbcUrl.substring(0, jdbcUrl.lastIndexOf("/")+1);

        Class.forName(driverClassName);
        try(Connection connection = DriverManager.getConnection(rawJdbcUrl, username, password);){
            ResultSet resultSet = connection.prepareStatement(queryDatabaseSQL).executeQuery();
            if(resultSet.next()){
                //说明数据库存在
            }else{
                connection.prepareStatement(createDatabaseSQL).executeUpdate();
            }
        }
    }

    @Override
    public String name() {
        return "执行创建数据库语句";
    }
}
